/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.springvision.yuanfeng.device.web;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.TooManyListenersException;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.web.BaseController;
import com.springvision.core.serialport.SerialPortUtils;
import com.springvision.yuanfeng.core.YfSerialPortListener;
import com.springvision.yuanfeng.device.entity.Device;
import com.springvision.yuanfeng.device.service.DeviceService;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.UnsupportedCommOperationException;

/**
 * 设备信息表Controller
 * @author 赵博
 * @version 2018-07-17
 */
@Controller
@RequestMapping(value = "${adminPath}/ctl/sp")
public class SerialPortController extends BaseController implements Serializable {

	/**
	 * 用做匹配
	 */
	public static Map<String, Device> _DEVICE_CACHE = new HashMap<String, Device>(4);

	@Autowired
	private YfSerialPortListener yfSerialPortListener;

	@Autowired
	private DeviceService deviceService;

	@ResponseBody
	@RequestMapping(value = "conn")
	public AjaxJson listen(@RequestParam(required = false) String com) {
		AjaxJson j = new AjaxJson();

		CommPortIdentifier port = SerialPortUtils.getSerialPort(com);
		System.err.println("串口------------------>" + port.getName() + "<---已经连接...");
		j.setMsg("删除设备表成功");

		try {
			yfSerialPortListener.initAndOpen(port);
		} catch (IOException | UnsupportedCommOperationException | TooManyListenersException | PortInUseException e) {
			e.printStackTrace();
		}
		return j;
	}

	@ResponseBody
	@RequestMapping(value = "close")
	public AjaxJson close() {
		AjaxJson j = new AjaxJson();
		yfSerialPortListener.close();
		return j;
	}

	/**
	 * 1。获取存量device code
	 * 2。写入DeviceMessageService._DEVICE_CACHE缓存
	 * 3.注在save和delete Device的时候都需要对缓存进行操作
	 * 4.改缓存只适用于离线版本
	 * @author: Elvin Zhao - 279152260@qq.com 
	 * @date: Created on 2018年7月17日 下午8:44:05
	 */
	@ResponseBody
	@RequestMapping(value = "init")
	@PostConstruct
	public void initDeviceMessageCache() {
		SerialPortController._DEVICE_CACHE.putAll(deviceService.findCodeMap());
//		System.err.println("_DEVICE_CACHE :" + SerialPortController._DEVICE_CACHE);// TODO
	}

}